package cn.ilikes.tools.hbase.jpa.persistences.context.operations;

import cn.ilikes.tools.hbase.jpa.clients.Client;
import cn.ilikes.tools.hbase.jpa.clients.JPAHBaseClientsException;
import cn.ilikes.tools.hbase.jpa.clients.nodes.Node;
import cn.ilikes.tools.hbase.jpa.clients.nodes.NodeLifeCycle.LifeCycle;
import cn.ilikes.tools.hbase.jpa.persistences.context.AbstractContext;
import cn.ilikes.tools.hbase.jpa.persistences.context.Operation;
import cn.ilikes.tools.hbase.jpa.persistences.context.OperationRunTimeException;
import cn.ilikes.tools.untils.PropertyAccessorHelper;

public class FindOperation<V> extends ContextOperation implements Operation<V> {

	private Class<V> entityClass;

	private Object key;

	public FindOperation(OperationType operationType, AbstractContext context, Class<V> entityClass, Object key) {
		super(operationType, context);
		this.entityClass = entityClass;
		this.key = key;

	}

	@Override
	public V exec() {
		AbstractContext abstractContext = getContext();
		Client client = abstractContext.getClient();
		try {
			Node node = client.findById(entityClass, key);
			if (node == null)
				return null;
			Node.switchNodeLifeCycle(node, LifeCycle.managed);
			abstractContext.putCache(key, node);
			return (V) node.getEntity();
		} catch (JPAHBaseClientsException e) {
			throw new OperationRunTimeException(e);
		}

	}

	@Override
	public boolean flush() {

		return true;
	}

	@Override
	public boolean rollback() {

		return true;
	}

	@Override
	public boolean initSub(AbstractContext context) {

		return true;
	}

}
